#!/usr/local/bin/python
# Rob Dennis - Lurchington Q. Delacroix
# Keasby - TV renamer
# Project Homepage: http://code.google.com/p/keasby/

import logging

from keasby_options import keasby_cl

##__USE_GUI__ = True
##
##try:
##    import wx
##except ImportError:
##    logging.warning("falling back to console mode")
##    __USE_GUI__ = False

def split_path(given_path):
    import os
    """returns a two-tuple of the two parent directories"""

    path,filename = os.path.split(given_path)
    path,parent_dir = os.path.split(path)
    path,parent_of_parent_dir = os.path.split(path)

    return parent_of_parent_dir, parent_dir


def choose_single(*args,**kwargs):

    if "list" in kwargs:
        return choose_single_first(kwargs["list"])
    else:
        return choose_single_first(args[0])


def choose_multiple(list,display_list,force):

    if __USE_GUI__:
        return NotImplemented
    else:
        return NotImplemented


def choose_single_first(list):

    for element in list:
        if element:
            return element


def cut_digit_from_string(piece_to_cut,basestring):
    import re

    logging.debug("an all-digit piece specified")

    try:
        reshaped_cut = r"0*"+str(int(piece_to_cut))
        logging.debug("cutting '%s' from %s",reshaped_cut,basestring)
        newstring = re.sub(reshaped_cut,"",basestring,1)
        logging.debug("resulting in %s",newstring)

    except AttributeError:
        logging.debug(piece_to_cut,"not found in",basestring)
        return basestring

    return newstring

def cut_substring_from_string(piece_to_cut,basestring):
    import re

    try:
        reshaped_cut = re.sub(r"\W+","\W+",piece_to_cut)
        logging.debug("cutting '%s' from %s",piece_to_cut,basestring)
        newstring = re.sub(r"(?i)"+reshaped_cut,"",basestring,1)
        logging.debug("resulting in %s",newstring)

    except AttributeError:
        logging.debug(pieceToCut,"not found in",basestring)
        return basestring

    return newstring


def cut_from_string(piece_to_cut,basestring):

    if piece_to_cut.isdigit():
        return cut_digit_from_string(piece_to_cut,basestring)
    else:
        return cut_substring_from_string(piece_to_cut,basestring)

def reshape_item(key,value):
    """
    to reshape dictionary items based on needs.
    currently casts an all-digit string to int, strips whitespace.
    Will return string of digits with a delimiter, eg. 01-02-03,
    as a list of integers, eg. [1,2,3].
    Returns a dictionary of {key:value}
    """

    if isinstance(value,basestring):
        value = value.strip()

    if (isinstance(value,basestring) and
            keasby_cl.opts.split_episode_char in value):

        return (key,get_multiple_episode_list(value))

    elif isinstance(value,basestring) and value.isdigit():
        return (key,int(value))

#    elif isinstance(value,basestring):
#        return (key,value.lower())

    else:
        return (key,value)

def reshape_dict(standard_dict):
    """
    Runs all items of a standard dictionary through reshape_item
    """

    return dict([reshape_item(key,value)
                        for key,value in standard_dict.iteritems()])



def get_multiple_episode_list(episode_string):
    """
    Takes a string similar to 01-02-03 and turns it into [1, 2, 3]
    """

    episode_list = []

    for episode in episode_string.split(keasby_cl.opts.split_episode_char):
        # if it's there's a split character, it's probably an
        # multi-episode string, which we'll be testing.

        if episode.isdigit():
            episode_list.append(int(episode))

    return episode_list


def all_keys(container,*test_list):
    """
    Returns the list of the values that exist in container, False if
    at least one key is not found
    """

    key_list = [container.get(item) for item in test_list]

    if all(key_list):
        return key_list

    else:
        return []

def swap_keys(input_dict, mapping_dict):
    """
    Switches the key names of input_dict for the key names of
    mapping dict. Example:

    input_dict = {"Original_Key":value, "normal_key":value2}
    mapping_dict = {"new_key":"Original_Key"}

    returns the result:

    {"new_key":value, "normal_key":value2}
    """

    if not mapping_dict:
        return input_dict


    mapped_dict = {}

    for tvep_key,input_key in mapping_dict.iteritems():
        mapped_dict[tvep_key] = input_dict[input_key]

    orig_pairs = [(key,value) for key,value in input_dict.iteritems()
                                if key not in mapping_dict.values()]

    mapped_dict.update(dict(orig_pairs))

    return mapped_dict



def dump(path):
    """
    Dumps the contents of the given cache path
    """

    return open(path,"rb").read()

def dump_zip(path,subfile):
    """
    Dumps the contents of the relative file in the provided zip file
    """
    import zipfile

    return zipfile.ZipFile(path,"r").read(subfile)

def rm_rf(path):
    """
    Emulates rm -rf functionality
    """
    import os
    import shutil

    if os.path.isdir(path):
        shutil.rmtree(path)

